import { LoginUserInfo } from '@/modules'
export default {
  namespaced: true,
  state: {
    token: localStorage.getItem('userInfo') ? localStorage.getItem('userInfo') : '',
    userInfo: localStorage.getItem('userInfo')
      ? JSON.parse(localStorage.getItem('userInfo') || '{}')
      : {
          avatar: '',
          userId: '',
          userName: ''
        }
  },
  mutations: {
    //存储token
    setToken(state: { token: string }, token: string) {
      state.token = token
      localStorage.token = token
    },
    // 存储userInfo
    setUserInfo(state: { userInfo: LoginUserInfo }, userInfo: LoginUserInfo) {
      state.userInfo = userInfo
      localStorage.userInfo = JSON.stringify(userInfo)
    },
    // 删除userInfo
    delUserInfo(state: { userInfo: LoginUserInfo }) {
      localStorage.clear()
    }
  },
  getters: {
    //获取token方法
    getToken(state: { token: string | null }) {
      if (state.token === '') {
        state.token = localStorage.getItem('token')
      }
      return state.token
    },
    //获取用户信息
    getUserInfo(state: { userInfo: LoginUserInfo }) {
      if (state.userInfo.userId === '') {
        let localUser = localStorage.getItem('userInfo')
        if (localUser) {
          state.userInfo = JSON.parse(localUser)
        }
      }
      return state.userInfo
    }
  }
}
